'use strict';

const crypto = require('crypto')
const db = uniCloud.database()
const uniID = require('uni-id')

// 乘法函数
function accMul(arg1,arg2) { 
	var m=0,s1=arg1.toString(),s2=arg2.toString(); 
	try{m+=s1.split(".")[1].length}catch(e){} 
	try{m+=s2.split(".")[1].length}catch(e){} 
	return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m) 
} 
// 加法函数
function accAdd(arg1,arg2){ 
	var r1,r2,m;
	try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0} 
	try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0} 
	m=Math.pow(10,Math.max(r1,r2)) 
	return (arg1*m+arg2*m)/m 
} 

exports.main = async (event, context) => {
	let res = {};
	console.log('event',event)
	const {
		data,
		uniIdToken
	} = event
	const payload = await uniID.checkToken(uniIdToken)
	console.log('payload',payload)
	if (payload.code > 0) {
		res = {
			code: 1001,
			msg: '用户身份验证失败，请重新登录'
		}
	}else{
		const order = db.collection('travel-order');
		const uid = payload.uid
		
		switch (event.operation){
			case "placeAnOrder":
				if(data){
					 const { goodsId,children,adult } = data;
					 const goods = db.collection('product')
					 // const dbCmd = db.command
					 // 获取订单中的商品信息
					 const goodsList = await goods.where({
					 	_id: goodsId
					 }).get()
					 if (!goodsList.data) {
					 	res =  {
					 		code: -2,
					 		msg: '商品信息错误'
					 	}
					 }
					 const goodsInfo = goodsList.data[0];
					 const price = goodsInfo.price;
					 // 计算总金额
					 // const totalFee = goodsInOrder.reduce((total, item) => {
					 // 	return total + goodsMap[item.id].price * item.amount
					 // }, 0)
					 const totalFee = accAdd(accMul(children,price),accMul(adult,price))
					 // 生成订单号的方式多种多样，实际应根据自己业务需求来，这里使用的是精确到秒的时间戳加用户id的hash前8位
					 const orderNo = parseInt(Date.now() / 1000) + crypto
					 	.createHash('md5')
					 	.update(uid, 'utf-8')
					 	.digest('hex').substring(0, 8);
					const orderResult = await order.add({
					 	uid,
					 	orderNo,
					 	totalFee,
					 	goodsInOrder:data,
					 	status: 1 // 1 - 未支付，2 - 已支付
					 })
					 if (!orderResult.id) {
					 	res = {
					 		code: -3,
					 		msg: '创建订单失败，请稍后再试'
					 	}
					 }else{
						// res = Object.assign({goodsInfo,totalFee},orderResult)
						res = {orderNo}
					 }
				}
				break;
			case "get-order-detail":
				const { orderNo } = data;
				// const orderList = await order.aggregate().match({
				// 	orderNo,
				// 	uid
				// }).unwind('$goodsInOrder').lookup({
				// 	from: 'product',
				// 	localField: 'goodsInOrder.id',
				// 	foreignField: '_id',
				// 	as: 'goodsDetail'
				// }).unwind('$goodsDetail').end()
				
				const orderList = await order.aggregate().match({
					orderNo,
					uid
				}).project({
					'goodsInOrder':1,
					'status':1,
					'totalFee':1,
					'orderNo':1,
					'_id':0
					}).lookup({
					from: 'product',
					localField: 'goodsInOrder.goodsId',
					foreignField: '_id',
					as: 'goodsDetail'
				}).unwind('$goodsDetail').project({
					'goodsDetail.name':1,
					'orderNo':1,
					'status':1,
					'totalFee':1
				}).end()
				if (orderList.data.length === 0) {
					res = {
						code: -1,
						msg: '订单不存在'
					}
					break;
				}
				let orderDetail = Object.assign({}, orderList.data[0])
				// delete orderDetail.goodsDetail
				// delete orderDetail.goodsInOrder
				
				// orderDetail.goodsList = orderList.data.map((item) => {
				// 	return item.goodsDetail
				// })
				res = orderDetail;
				break;
			default:
				res = {
				  code: 403,
				  msg: '非法访问'
				}
				break;
		}
	}
	return res
};
